
import os
import json
import copy
from collections import OrderedDict

from common.libs.Helper import getCurrentTime,generateUUID
from common.libs.Log import logger

from db.models import session, Device

class DeviceService(object):
    def __init__(self):
        pass

    def getAll(self):
        res = session.query(Device).all()
        data = []
        for r in res:
            data.append({
                'id':r.id,
                'name':r.name,
                'sn':r.sn,
                'model':r.model,
                'position':r.position,
                'image':r.image,
                'created_time':r.created_time,
                'updated_time':r.updated_time
            })
        return data

    def delete(self, _id):
        device = session.query(Device).get(_id)
        if device:
            session.delete(device)
            session.commit()
            return True

    def add(self, data):
        res = {'code':200,'msg':'添加成功'}
        device = session.query(Device).filter_by(sn=data['sn']).first()
        if device:
            res['code'] = -1
            res['msg'] = '添加失败, 设备SN重复'
            return res
        device = Device(
            name=data['name'], 
            sn=data['sn'], 
            position=data['position'], 
            model=data['model'], 
            image='', 
            created_time=getCurrentTime(), 
            updated_time=getCurrentTime()
            )
        session.add(device)
        session.commit()
        return res

    def modify(self, data):
        res = {'code':200,'msg':'修改成功'}
        device = session.query(Device).filter_by(id=data['id']).first()
        if not device:
            res['code'] = -1
            res['msg'] = '修改失败, 设备不存在'
            return res
        device.name=data['name']
        device.sn=data['sn']
        device.position=data['position']
        device.model=data['model']
        device.updated_time=getCurrentTime()
        session.commit()
        return res

CONFIG_PATH = os.getcwd()+'/conf/devices.json'
class DeviceServiceJson(object):
    devices = {}
    def __init__(self):
        pass

    def read(self):
        try:
            with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
                devices = json.loads(f.read(), object_pairs_hook=OrderedDict)
                self.devices = sorted(devices, key=lambda k: k['id'])
                # self.devices = copy.deepcopy(devices)
                return devices
        except Exception as e:
            logger.info(e)
            return False

    def write(self):
        try:
            save = json.dumps(self.devices, indent=4)
            with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
                f.write(save)
        except Exception as e:
            logger.info(e)
            return False

    def getAll(self):
        devices = self.read()
        self.devices = copy.deepcopy(devices)
        return devices

    def delete(self, device):
        res = {'code':200,'msg':'删除成功'}
        key = device['key']
        for i in range(0, len(self.devices)):
            if key == self.devices[i]['key']:
                del self.devices[i]
                self.write()
                return res
        res['code'] = -1
        res['msg'] = '删除失败, 设备不存在'
        return res

    def add(self, data):
        res = {'code':200,'msg':'添加成功'}
        for d in self.devices:
            if data['value']['sn'] == d['value']['sn']:
                res['code'] = -1
                res['msg'] = '添加失败, 设备SN重复'
                return res
        self.devices.append({
            "id": len(self.devices),
            "key": generateUUID(),
            "value": data['value']
           }
        )
        self.write()
        return res

    def modify(self, data):
        res = {'code':200,'msg':'修改成功'}
        for i in range(0, len(self.devices)):
            if data['key'] == self.devices[i]['key']:
                self.devices[i] = data
                self.write()
                return res
        res['code'] = -1
        res['msg'] = '修改失败, 设备不存在'
        return res
